package com.jy.wms.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.joyi.gate.safety.vo.UserInfo;
import com.jy.wms.common.annotions.BaseServiceDescribe;
import com.jy.wms.common.base.BaseService;
import com.jy.wms.common.base.ServiceException;
import com.jy.wms.common.base.SucessException;
import com.jy.wms.dao.*;
import com.jy.wms.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
    * @ClassName: WmsReceiptTaskPdaService.java
    * @Description: TODO(这里用一句话描述这个类的作用)
    * @Author Liyi
    * @Date Thu Nov 30 10:04:14 CST 2017
    */

    @Service
    public class WmsReceiptTaskPdaService extends BaseService<WmsReceiptTaskPdaMapper,WmsReceiptTaskPda> {

        @Autowired
        private WmsOwnerMapper wmsOwnerMapper;
        @Autowired
        private WmsEstimatedArrivalOrderDetailedMapper wmsEstimatedArrivalOrderDetailedMapper;
         @Autowired
        private WmsReceiptTaskPdaDetailedMapper wmsReceiptTaskPdaDetailedMapper;
        @Autowired
         private WmsEstimatedArrivalOrderMapper wmsEstimatedArrivalOrderMapper;
         @Autowired
         private WmsPdaMsgMapper wmsPdaMsgMapper;
    @Autowired
    private WmsPalletSortingService wmsPalletSortingService;
    @BaseServiceDescribe(moduleName = "PDA收货任务",btnName = "查看PDA收货任务明细")
         public List<WmsReceiptTaskPdaDetailed> getPdaDetailed(String yqid) throws ServiceException {
        try {
            WmsReceiptTaskPda wmsReceiptTaskPda = dao.getByYqid(yqid);
            if(wmsReceiptTaskPda != null){
                List<WmsReceiptTaskPdaDetailed> list = dao.getDetailedById(wmsReceiptTaskPda.getId());
                return list;
            }else{
                throw new ServiceException("该ASN订单没有PDA收货任务");
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("根据预期到货通知单ID查询对应明细失败",e);
        }
    }


     /**
     * 插入一条记录
     * @param map 必要参数
     * @return int
     */
     @BaseServiceDescribe(moduleName = "PDA收货任务",btnName = "生成PDA收货任务")
     @Transactional
    public void baseInsert(Map<String,Object> map , UserInfo userinfo, List<SysHz> hz)throws SucessException,ServiceException,RuntimeException {
         WmsEstimatedArrivalOrder wmsEstimatedArrivalOrder = wmsEstimatedArrivalOrderMapper.selectById(String.valueOf(map.get("id")));
        if(wmsEstimatedArrivalOrder.getAsnzt().equals("0") && wmsEstimatedArrivalOrder.getShzt().equals("1") && wmsEstimatedArrivalOrder.getSczt().equals("0")){
            //生成wms_receipt_task_pda数据
            WmsReceiptTaskPda wmsReceiptTaskPda = new WmsReceiptTaskPda();
            Map<String,Object> kwMap = null;
            WmsOwner wmsOwner = null;
            if(hz.size()>0){
                wmsReceiptTaskPda.setSshzid(hz.get(0).getHzid());
                wmsOwner = wmsOwnerMapper.selectById(hz.get(0).getHzid());
                wmsReceiptTaskPda.setBxyxj(String.valueOf(wmsOwner.getYxj()));
                kwMap = wmsOwnerMapper.getAllKw(wmsOwner.getId());
            }
            wmsReceiptTaskPda.setYqid(String.valueOf(map.get("id")));
            wmsReceiptTaskPda.setYqdh(String.valueOf(map.get("asnbh")));
            wmsReceiptTaskPda.setRyid(String.valueOf(map.get("ryid")));
            wmsReceiptTaskPda.setYxj(String.valueOf(map.get("yxj")));
            wmsReceiptTaskPda.setCjr(userinfo.getUser().getName());
            wmsReceiptTaskPda.setShlx(String.valueOf(map.get("mpzt")));
            wmsReceiptTaskPda.setCkid(String.valueOf(userinfo.getUser().getOrgId().get(0)));
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            wmsReceiptTaskPda.setScsj(sdf.format(new Date()));
            wmsReceiptTaskPda.setGysmc(String.valueOf(map.get("gysmc")));
            wmsReceiptTaskPda.setCgdid(wmsEstimatedArrivalOrder.getDycgdid());
            wmsReceiptTaskPda.setSmhpm(wmsOwner.getCmhpm());
            //插入PDA任务主表信息
            Integer cout = dao.baseInsertSelective(wmsReceiptTaskPda);
            //查询预期到货通知单明细列表
            List<WmsEstimatedArrivalOrderDetailed> detaileds = wmsEstimatedArrivalOrderDetailedMapper.getBySsyqdid(String.valueOf(map.get("id")));
            WmsReceiptTaskPdaDetailed wmsReceiptTaskPdaDetailed = new WmsReceiptTaskPdaDetailed();
            //存放ASN明细下货品对应包装及换算量信息
            Map<String,Object> goodsMap = null;
//            List<WmsReceiptTaskPdaDetailed> addDetaileds = new ArrayList<WmsReceiptTaskPdaDetailed>();
            //如果选择 码盘状态为未码盘（常规）则查询ASN明细信息
            if(String.valueOf(map.get("mpzt")).equals("0")){
                List<WmsReceiptTaskPdaDetailed> list = new ArrayList<WmsReceiptTaskPdaDetailed>();
                for (WmsEstimatedArrivalOrderDetailed detailed : detaileds) {
                    wmsReceiptTaskPdaDetailed.setPdashid(wmsReceiptTaskPda.getId());
                    wmsReceiptTaskPdaDetailed.setYqdhmxid(detailed.getId());
                    wmsReceiptTaskPdaDetailed.setHpid(detailed.getHpid());
                    goodsMap = wmsReceiptTaskPdaDetailedMapper.getGoodsById(detailed.getHpid());
                    wmsReceiptTaskPdaDetailed.setHpmc(String.valueOf(goodsMap.get("hpmc")));
                    wmsReceiptTaskPdaDetailed.setHpbh(String.valueOf(goodsMap.get("hpbh")));
                    wmsReceiptTaskPdaDetailed.setPc(detailed.getHppc());
                    wmsReceiptTaskPdaDetailed.setSl(detailed.getYqsl());
                    wmsReceiptTaskPdaDetailed.setGys(String.valueOf(map.get("gysmc")));
                    wmsReceiptTaskPdaDetailed.setScrq(detailed.getScrq());
                    if(wmsOwner != null){
                        wmsReceiptTaskPdaDetailed.setTjkw(String.valueOf(kwMap.get("djcwMc")));
                        wmsReceiptTaskPdaDetailed.setTjkwid(wmsOwner.getDjcwid());
                    }
                    wmsReceiptTaskPdaDetailed.setZdwmc(String.valueOf(goodsMap.get("zdwmc")));
                    wmsReceiptTaskPdaDetailed.setXdwmc(String.valueOf(goodsMap.get("xdwmc")));
                    wmsReceiptTaskPdaDetailed.setHsl(String.valueOf(goodsMap.get("hsl")));
                    wmsReceiptTaskPdaDetailed.setTh("0");
                    wmsReceiptTaskPdaDetailed.setLpnid("");
                    wmsReceiptTaskPdaDetailed.setLpn("");
                    wmsReceiptTaskPdaDetailed.setCgmxid(detailed.getDycgmxid());
                    wmsReceiptTaskPdaDetailed.setSxrq(detailed.getSxrq());
                    wmsReceiptTaskPdaDetailed.setTjsjkwid("");
                    wmsReceiptTaskPdaDetailed.setGg(detailed.getGg());
                    wmsReceiptTaskPdaDetailedMapper.baseInsertSelective(wmsReceiptTaskPdaDetailed);
                }
            }else if((String.valueOf(map.get("mpzt"))).equals("1")){
                //如果选择 码盘状态为已码盘（码盘）则查询码盘信息
                for (WmsEstimatedArrivalOrderDetailed detailed : detaileds) {
                    List<WmsPalletSorting> list = dao.getPalletSorting(detailed.getId());
                    for (WmsPalletSorting wmsPalletSorting : list) {
                        wmsReceiptTaskPdaDetailed.setPdashid(wmsReceiptTaskPda.getId());
                        wmsReceiptTaskPdaDetailed.setYqdhmxid(detailed.getId());
                        wmsReceiptTaskPdaDetailed.setHpid(detailed.getHpid());
                        goodsMap = wmsReceiptTaskPdaDetailedMapper.getGoodsById(detailed.getHpid());
                        wmsReceiptTaskPdaDetailed.setHpmc(String.valueOf(goodsMap.get("hpmc")));
                        wmsReceiptTaskPdaDetailed.setHpbh(String.valueOf(goodsMap.get("hpbh")));
                        wmsReceiptTaskPdaDetailed.setPc(detailed.getHppc());
                        wmsReceiptTaskPdaDetailed.setSl(new Long(Math.round(Double.valueOf(wmsPalletSorting.getYqmpsl()))).toString());
                        wmsReceiptTaskPdaDetailed.setGys(String.valueOf(map.get("gysmc")));
                        wmsReceiptTaskPdaDetailed.setScrq(detailed.getScrq());
                        if(wmsOwner != null){
                            wmsReceiptTaskPdaDetailed.setTjkw(String.valueOf(kwMap.get("djcwMc")));
                            wmsReceiptTaskPdaDetailed.setTjkwid(wmsOwner.getDjcwid());
                        }
                        wmsReceiptTaskPdaDetailed.setZdwmc(String.valueOf(goodsMap.get("zdwmc")));
                        wmsReceiptTaskPdaDetailed.setXdwmc(String.valueOf(goodsMap.get("xdwmc")));
                        wmsReceiptTaskPdaDetailed.setHsl(String.valueOf(goodsMap.get("hsl")));
                        wmsReceiptTaskPdaDetailed.setTh( wmsPalletSortingService.th(wmsPalletSorting.getKwid(), detailed.getHpid()));
                        wmsReceiptTaskPdaDetailed.setLpnid(wmsPalletSorting.getId());
                        wmsReceiptTaskPdaDetailed.setLpn(wmsPalletSorting.getLpn());
                        wmsReceiptTaskPdaDetailed.setCgmxid(detailed.getDycgmxid());
                        wmsReceiptTaskPdaDetailed.setSxrq(detailed.getSxrq());
                        wmsReceiptTaskPdaDetailed.setTjsjkwid(wmsPalletSorting.getKwid());
                        wmsReceiptTaskPdaDetailed.setGg(detailed.getGg());
                        wmsReceiptTaskPdaDetailedMapper.baseInsertSelective(wmsReceiptTaskPdaDetailed);
                    }
                }
            }
//            Integer detailedCount =  wmsReceiptTaskPdaDetailedMapper.baseInsertAll(addDetaileds);
            wmsEstimatedArrivalOrder.setSczt("1");
            Integer updateAsnCount = wmsEstimatedArrivalOrderMapper.baseUpdateByPrimaryKeySelective(wmsEstimatedArrivalOrder);
            //生成PDA消息推送
            WmsPdaMsg wmsPdaMsg = new WmsPdaMsg();
            String[] ryids = String.valueOf(map.get("ryid")).split(",");
            for (String ryid : ryids) {
                wmsPdaMsg.setRyid(ryid);
                wmsPdaMsg.setBt(wmsEstimatedArrivalOrder.getAsnbh());
                wmsPdaMsg.setXx(wmsReceiptTaskPda.getScsj() + " 下发收货任务");
                Integer msgCount = wmsPdaMsgMapper.baseInsertSelective(wmsPdaMsg);
                if(msgCount == 0){
                    throw new RuntimeException("生成PDA收货任务失败，数据未插入数据库");
                }
            }
            if(cout == 1){
                throw new SucessException("生成PDA收货任务成功");
            }else{
                throw new RuntimeException("生成PDA收货任务失败，数据未插入数据库");
            }
        }else{
            throw new ServiceException("生成PDA收货任务失败，请确定ASN订单的ASN状态为创建，审核状态已审核并且未生成收货任务");
        }
    }

   /**
    * 插入一条记录（匹配有值的字段）
    * @param entity 实体对象
    * @return int
    */
    public Integer baseInsertSelective(WmsReceiptTaskPda entity){
         return dao.baseInsertSelective( entity);
    }

   /**
    * 删除（根据主键ID删除）
    * @param id 主键
    * @return int
    */
    public Integer baseDeleteByPrimaryKey(String id){
         return dao.baseDeleteByPrimaryKey( id);
    }

   /**
    * 删除（根据ID 批量删除）
    * @param idList 主键ID列表
    * @return int
    */
    public Integer baseDeleteBathPrimaryKeys(List<String> idList){
         return dao.baseDeleteBathPrimaryKeys( idList );
    }

    /**
    * 分页查询
    * @param entity 实体
    * @return Page<WmsReceiptTaskPda>
    */
    @BaseServiceDescribe(moduleName = "PDA收货任务",btnName = "查询未完成的PDA收货任务")
    public Page<WmsReceiptTaskPda> baseSelectPage(WmsReceiptTaskPda entity ) throws ServiceException {
        try {
            PageHelper.startPage(entity.getPage(),entity.getRows());
            return (Page<WmsReceiptTaskPda>)dao.baseSelectPage( entity );
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("查询未完成的PDA收货任务失败",e);
        }
    }

   /**
    * 查询（根据主键ID查询）
    * @param id 主键ID
    * @return WmsReceiptTaskPda
    */
    public WmsReceiptTaskPda baseSelectByPrimaryKey(String id ){
         return dao.baseSelectByPrimaryKey( id );
    }

   /**
    * 查询（根据ID 批量查询）
    * @param idList 主键ID列表
    * @return list
    */
    public Integer baseSelectBathPrimaryKeys(List<WmsReceiptTaskPda> idList ){
         return dao.baseSelectBathPrimaryKeys( idList );
    }

   /**
    *修改 （匹配有值的字段）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKeySelective(WmsReceiptTaskPda entity){
         return dao.baseUpdateByPrimaryKeySelective( entity);
    }

   /**
    *修改（根据主键ID修改）
    * @param entity 主键ID列表
    * @return int
    */
    public Integer baseUpdateByPrimaryKey(WmsReceiptTaskPda entity){
         return dao.baseUpdateByPrimaryKey( entity);
    }

}
